package dpinfrastructure;

import java.util.Date;
import java.util.Random;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.sh.dpinfrastructure.exception.DPException;
import net.sh.dpinfrastructure.sql.DPSqlAppender;
import net.sh.dpinfrastructure.support.spring.configuration.DPInfrastructureStarter;

@Service
public class DPTestService {

    @Resource
    private JdbcTemplate jdbcTemplate;
    
    private String testTableName = "t_test";
    
    @Transactional
    public void testTransactionFailed() {
        DPSqlAppender insertSqlAppender = new DPSqlAppender();
        insertSqlAppender.append("INSERT INTO ").append(testTableName).append(" (name, num, update_date, update_time) VALUES (?, ?, ?, ?)");
        String name = "开始事务回滚，插入应该失败";
        long num = new Random().nextLong();
        Date now = new Date();
        jdbcTemplate.update(insertSqlAppender.toString(), name, num, new java.sql.Date(now.getTime()), new Date());
        throw new DPException("开启事务");
    }
    
    @Transactional
    public void testTransactionSuccess() {
        DPSqlAppender insertSqlAppender = new DPSqlAppender();
        insertSqlAppender.append("INSERT INTO ").append(testTableName).append(" (name, num, update_date, update_time) VALUES (?, ?, ?, ?)");
        String name = "开始事务提交， 插入应该成功";
        long num = new Random().nextLong();
        Date now = new Date();
        jdbcTemplate.update(insertSqlAppender.toString(), name, num, new java.sql.Date(now.getTime()), new Date());
    }
    
    public void testNoTransaction() {
        DPSqlAppender insertSqlAppender = new DPSqlAppender();
        insertSqlAppender.append("INSERT INTO ").append(testTableName).append(" (name, num, update_date, update_time) VALUES (?, ?, ?, ?)");
        String name = "没有开启事务，插入应该成功";
        long num = new Random().nextLong();
        Date now = new Date();
        jdbcTemplate.update(insertSqlAppender.toString(), name, num, new java.sql.Date(now.getTime()), new Date());
        throw new DPException("开启事务");
    }
    
}
